import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Layout, Menu, Empty, Button } from 'antd';
import { connect, useSelector } from 'react-redux'
import './index.css'
import { SYSTEMNAME } from '../../redux/constant';
import { extractProp } from '../../utils/array';
import { getRights } from '../../utils/request/get.js';
import { refresh } from '../../utils/common';

const { Sider } = Layout;
const checkedItems = []
let rightData = []

const getItem = (label, key, children) => {
	return { key, children, label }
}

const checkPagePermission = (item) => {
	return item.pagePermission === 1 && rightData.includes(item.key)
}

// 采用递归将侧边栏分类并整理为 menu 数组的格式
const renderMenu = (menu, result = []) => {
	let menuArr = []
	for (let i = 0; i < menu.length; i++) {
		const item = menu[i];
		if (!checkedItems.includes(item.key)) {
			checkedItems.push(item.key)
			// 若递归的 item 项没有 children 属性，则为 false，加 ？ 是为了解决 ‘读取不到 length 属性的问题’
			if (item.children?.length > 0 && checkPagePermission(item)) {
				menuArr = renderMenu(item.children)
			}
			let obj = menuArr.length > 0 ?
				getItem(item.title, item.key, menuArr) :
				getItem(item.title, item.key)
			if (checkPagePermission(item)) { // 只将 pagePermission 为 1 且 当前用户拥有的权限 放入侧边栏
				result.push(obj)
			}
		}
	}
	return result
}

function SideMenu(props) {
	let navigate = useNavigate()
	let location = useLocation()
	const [items, setItems] = useState([])
	// const [rights, setRights] = useState([])
	const token = useSelector(state => state.TokenReducer.token)

	// 设置拉伸
	const { collapsed } = props.CollapsedReducer
	// 获取当前所在的页面路径
	const selectedKey = location.pathname
	// 获取当前打开的侧边栏路径
	const openKey = ["/" + location.pathname.split('/')[1]]

	useEffect(() => {
		async function fetchData() {
			// 获取页面缓存
			if (token) {
				const res = await getRights(token.roleId)
				rightData = extractProp("key", res)
				// console.log(rightData);
				setItems(renderMenu(res))
			}
		}
		fetchData()
	}, [token])


	// 获取点击跳转的路由地址并更改
	const onClick = (e) => {
		// 实现跳转到点击的路由界面
		navigate(e.key)
	}

	const noData = () => {
		return (
			<Empty description={"数据请求失败，请刷新重试"}>
				<Button onClick={refresh}>刷新</Button>
			</Empty>
		)
	}

	const bgColor = "rgb(204, 232, 207)"
	const color = "black"

	return (
		<Sider trigger={null} collapsible collapsed={collapsed}
			style={{
				backgroundColor: bgColor,
				color
			}}>
			<div style={{ display: "flex", height: "100%", "flexDirection": "column" }}>
				<div className="logo">{SYSTEMNAME}</div>
				<div className='hide' style={{ flex: 1, "overflow": "auto" }}>
					{items.length === 0 ? noData() : <Menu theme="light" mode="inline"
						style={{ backgroundColor: bgColor, color }}
						selectedKeys={selectedKey}
						defaultOpenKeys={openKey}
						items={items}
						onClick={onClick} />}
				</div>
			</div>
		</Sider>
	)
}

export default connect(
	state => ({
		CollapsedReducer: state.CollapsedReducer
	})
)(SideMenu)